#!/bin/env python

from metaimage import baseX
from datetime import datetime 

class DateTimeEncoding:
    name = None
    def __init__(self, timestamp, args):
        self.prefix = args.prefix + timestamp.strftime('%Y%m%d')
        self.suffix = args.suffix

        self.alphabet = args.alphabet
        self.alphabet_length = len(self.alphabet)

        # seconds in a day = 86400 (24*60*60)
        # ensure that we have enough digits to encode time
        self.digits = args.digits
        while self.alphabet_length**self.digits < 86400:
            self.digits += 1 

        tbits = 17 # seconds in a day needs 17 bit (len(bin(24*60*60)) - 2)
        time  = (timestamp.hour*3600 + timestamp.minute*60 + timestamp.second, tbits)
        count = (0, self._bits_() - tbits)

        self.timecount = baseX.Multiencoding([time, count])
        self._evaluate_()

    def _bits_(self): # bits available with current digits
        return len(bin(self.alphabet_length**self.digits)) - 2

    def _evaluate_(self):
        self.name  = self.prefix 
        self.name += baseX.encode(int(self.timecount), self.alphabet, self.digits)
        self.name += self.suffix

    def renew(self):
        time, tbits = self.timecount[0]
        count, cbits = self.timecount[1]
        count += 1
        if cbits < len(bin(count)) - 2:
            self.digits += 1
            cbits = self._bits_() - tbits

        self.timecount[1] = (count, cbits)
        self._evaluate_()

    def __str__(self):
        return self.name

    def __int__(self):
        return int(self.timecount)


class DTE5b26(DateTimeEncoding):
    def __init__(self, image, args):
        args.alphabet = baseX.Alphabet.Base26
        args.digits = 5
        super().__init__(image.timestamp, args)


def switch(scheme):
    try:
        return {
            'default' : DTE5b26,
            'dte5b26' : DTE5b26
        }[scheme]
    except Exception as err:
        print(err)
        return DTE5b26


#if __name__ == '__main__':
#    fmt = '%Y:%m:%d %H:%M:%S'
#
#    d1 = datetime.strptime('2013:04:10 21:50:08', fmt)
#    d2 = datetime.strptime('2013:04:10 00:09:47', fmt)
#
#    n1 = YYMD5X(d1, baseX.Alphabet.Base36, '', '', 5)
#    n2 = YYMD5X(d2, baseX.Alphabet.Base36, '', '', 5)
#
#    print(str(n1.timecount), str(n2.timecount))
#    print(str(n1), str(n2))

